package com.mall.b2c.controller;

import com.mall.b2c.service.StaticService;
import com.mall.common.bean.Message;
import com.mall.common.controller.BaseController;
import com.mall.common.domain.content.ArticleCategoryDomain;
import com.mall.common.domain.content.ArticleDomain;
import com.mall.common.service.ArticleCategoryService;
import com.mall.common.service.ArticleService;
import com.mall.common.validation.annotation.RequiredFieldValidator;
import com.mall.common.validation.annotation.Validations;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 后台Action类 - 静态化
 * @author lishuai 2013-08-03
 *
 */
@Controller
@RequestMapping("/admin/b2c/static")
public class StaticController extends BaseController {

	//静态化页面
	@Resource
	ArticleService articleService;
	@Resource
	ArticleCategoryService categoryService;
	@Resource
	StaticService staticService;
	
	//静态化处理
	@RequestMapping(value="/build", method=RequestMethod.GET)
	public String build(Model model) {
		model.addAttribute("defaultBeginDate", DateUtils.addDays(new Date(), -7));
		model.addAttribute("defaultEndDate", new Date());
		JSONArray arr = new JSONArray();
		List<ArticleCategoryDomain> articleCategoryList = categoryService.getAll();;
		if(articleCategoryList != null && articleCategoryList.size() > 0){
			for(ArticleCategoryDomain articleCategory : articleCategoryList){
				JSONObject jObject = new JSONObject();
				jObject.put("id", articleCategory.getId());
				jObject.put("pid", articleCategory.getParentId());
				jObject.put("text", articleCategory.getName());
				arr.add(jObject);
			}
		}
		model.addAttribute("articleCategoryByJson", arr.toString());
		return "/admin/b2c/template/build";
	}
	
	/**
	 * 静态化操作
	 * @return
	 */
	@RequestMapping(value="/buildStatic", method=RequestMethod.POST)
	@ResponseBody
	public Message buildStatic(
			Long articleCategoryId, @DateTimeFormat(pattern="yyyy-MM-dd") Date beginDate,
			@DateTimeFormat(pattern="yyyy-MM-dd") Date endDate, HttpServletResponse response){


		int i = 0;
		List<ArticleDomain> list = articleService.getAticles(articleCategoryId, beginDate, endDate);
		for (ArticleDomain article : list)
		{
			try {
				i += staticService.build(article);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return successMessage;
	}
}
